package com.wonyesoft.wuliu.acticity.order;

import httptools.HttpJsonTool;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import tools.ImageFactory;

import javabeen.LinkManBeen;
import javabeen.OrderInfoBeen;
import javabeen.passlocations;

import View.DatePickerFragment;
import View.DatePickerFragment.onChoseData;
import View.InPutDialog;
import View.InPutDialog.getChoseTYPE;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.CalendarContract.Colors;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.android.bbalbs.common.a.a;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.google.gson.Gson;
import com.google.zxing.datamatrix.DataMatrixReader;
import com.lidroid.xutils.BitmapUtils;
import com.wonyesoft.wuliu.AppContent;
import com.wonyesoft.wuliu.R;
import com.wonyesoft.wuliu.acticity.AddCargoLastActivity;
import com.wonyesoft.wuliu.acticity.AddCargoMapActivity;
import com.wonyesoft.wuliu.acticity.UserLoginActivity;
import com.wonyesoft.wuliu.acticity.base.BaseActivity;
import com.wonyesoft.wuliu.acticity.user.UserLinkMan_Activity;
import com.wonyesoft.wuliu.acticity.utils.FileUtils;
import com.wonyesoft.wuliu.acticity.utils.PhotoUtils;
import com.wonyesoft.wuliu.acticity.utils.StringUtils;
import com.wonyesoft.wuliu.api.GagApi;

/**
 * * @author 作者 陈修园E-mail: *
 * 
 * @date 创建时间：2015-6-11 下午1:33:32 * @version 1.0 * @parameter 下单Activity * @since
 * 
 *       * @return
 * */
public class AddCargoOrderActivity extends BaseActivity {
	HashMap<String, String> imageMap = new HashMap<String, String>();
	HashMap<String, Object> infoMap = new HashMap<String, Object>();

	private String flag = "-1";

	List<String> destinations;
	private String carry_man_need = "0";

	private String needreceipt = "2";

	private AppContent app;
	// private int ImageID;

	// 图片在SD卡中的缓存路径
	private static final String IMAGE_PATH = Environment
			.getExternalStorageDirectory().toString()
			+ File.separator
			+ "tczh"
			+ File.separator + "Images" + File.separator;

	String mTakePicturePath;
	private EditText receivername_1;

	private EditText receiverphone_1;

	private TextView destination_1;

	private EditText receivername_2;

	private EditText receiverphone_2;

	private TextView destination_2;

	private EditText receivername_3;

	private EditText receiverphone_3;

	private TextView destination_3;

	private EditText cargoname;

	private EditText cargophone;

	private TextView origin;

	private EditText expectprice;

	private TextView suggestprice;

	private TextView payway;

	private TextView payman;

	private RelativeLayout carryname;

	private TextView insure;

	private RelativeLayout callbacklist;
	private TextView cargoremark;

	private ImageView photo1;

	private ImageView photo2;

	private ImageView photo3;

	private Button systeamprice;

	private Button upload;

	private GeoCoder mSearch = null;

	private ActionClick actionClick;

	private ImageClick imageClick;

	private boolean isOriginFlag = false;

	private String cartype;
	private String pay_way;
	private String pay_man;

	View show_receive_view_1;
	View receive_view_1;
	View show_receive_view_2;
	View receive_view_2;

	private boolean receive_2_open;

	private boolean receive_3_open;

//	private List<HashMap<String, Object>> saveGeoCode = new ArrayList<HashMap<String, Object>>();
	private HashMap<String, Object>[] saveGeoCode;
	private HashMap<String, Object> originCoordinate = new HashMap<String, Object>();
	private boolean receiveAddress_1 = false;
	private boolean receiveAddress_2 = false;
	private boolean receiveAddress_3 = false;
	private boolean receiveAddress_4 = false;
	private int address_tyep = 1;

	HashMap<String, Object> address_dataMap = new HashMap<String, Object>();

	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		SDKInitializer.initialize(AppContent.getContext());
		setContentView(R.layout.activity_add_cargo_order);
		Intent intent = getIntent();
		cartype = intent.getIntExtra("car_type_id", 0) + "";
		app = (AppContent) getApplication();
		app.addActivity(this);
		infoMap.put("cartypeid", cartype);
		actionClick = new ActionClick();
		imageClick = new ImageClick();
		Ini_BaiduMap();
		IniId();
		saveGeoCode=new HashMap[3];
		for (int i = 0; i < 3; i++) {
			saveGeoCode[i] = new HashMap<String, Object>();
			//saveGeoCode.add(hashMap);
		}
		setDataToUIbyModificationOrder();

		if (savedInstanceState != null) {
			getSaveData(savedInstanceState);
		}

	}

	private void setDataToUIbyModificationOrder() {
		Intent intent = getIntent();
		OrderInfoBeen orderInfoBeen = (OrderInfoBeen) intent
				.getSerializableExtra("orderData");
		if (orderInfoBeen == null) {
			return;
		}
		List<passlocations> passlocations = orderInfoBeen.getPasslocations();
		int i = passlocations.size();
		if (i == 1) {
			receivername_1.setText(orderInfoBeen.getPasslocations().get(0)
					.getReceivername());
			receiverphone_1.setText(orderInfoBeen.getPasslocations().get(0)
					.getReceiverphone());
		}
		if (i == 2) {
			receivername_1.setText(orderInfoBeen.getPasslocations().get(0)
					.getReceivername());
			receiverphone_1.setText(orderInfoBeen.getPasslocations().get(0)
					.getReceiverphone());
			receivername_2.setText(orderInfoBeen.getPasslocations().get(0)
					.getReceivername());
			receiverphone_2.setText(orderInfoBeen.getPasslocations().get(0)
					.getReceiverphone());
		}
		if (i == 3) {
			receivername_1.setText(orderInfoBeen.getPasslocations().get(0)
					.getReceivername());
			receiverphone_1.setText(orderInfoBeen.getPasslocations().get(0)
					.getReceiverphone());
			receivername_2.setText(orderInfoBeen.getPasslocations().get(0)
					.getReceivername());
			receiverphone_2.setText(orderInfoBeen.getPasslocations().get(0)
					.getReceiverphone());
			receivername_3.setText(orderInfoBeen.getPasslocations().get(0)
					.getReceivername());
			receiverphone_3.setText(orderInfoBeen.getPasslocations().get(0)
					.getReceiverphone());
		}
	}

	private void Ini_BaiduMap() {
		mSearch = GeoCoder.newInstance();
		// mSearch.setOnGetGeoCodeResultListener(this);
	}

	private void IniId() {
		TextView textView = (TextView) findViewById(R.id.head_title);
		textView.setVisibility(View.VISIBLE);
		textView.setText("在线下单");
		ImageView head_left = (ImageView) findViewById(R.id.head_left);
		head_left.setVisibility(View.VISIBLE);
		head_left.setImageResource(R.drawable.back_normal);
		head_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				AddCargoOrderActivity.this.finish();
			}
		});

		TextView head_right_text = (TextView) findViewById(R.id.linkman_info);
		// head_right_text.setVisibility(View.VISIBLE);
		// head_right_text.setText("我的常用联系人");
		head_right_text.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AddCargoOrderActivity.this,
						UserLinkMan_Activity.class);
				startActivityForResult(intent, 520);
			}
		});
		receivername_1 = (EditText) findViewById(R.id.receivername_1);

		receiverphone_1 = (EditText) findViewById(R.id.receiverphone_1);
		destination_1 = (TextView) findViewById(R.id.destination_1);
		destination_1.setOnClickListener(actionClick);
		receivername_2 = (EditText) findViewById(R.id.receivername_2);
		receiverphone_2 = (EditText) findViewById(R.id.receiverphone_2);
		destination_2 = (TextView) findViewById(R.id.destination_2);
		destination_2.setOnClickListener(actionClick);
		receivername_3 = (EditText) findViewById(R.id.receivername_3);
		receiverphone_3 = (EditText) findViewById(R.id.receiverphone_3);
		destination_3 = (TextView) findViewById(R.id.destination_3);
		destination_3.setOnClickListener(actionClick);
		cargoname = (EditText) findViewById(R.id.cargoname);
		cargophone = (EditText) findViewById(R.id.cargophone);
		origin = (TextView) findViewById(R.id.origin);
		origin.setOnClickListener(actionClick);
		expectprice = (EditText) findViewById(R.id.expectprice);
		payway = (TextView) findViewById(R.id.payway);
		View cargoinfo_cargotype = findViewById(R.id.cargoinfo_cargotype);
		cargoinfo_cargotype.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Toast.makeText(AddCargoOrderActivity.this, "目前只开通线下支付手段",
						Toast.LENGTH_LONG).show();
				// showChosepayway();
			}
		});
		payman = (TextView) findViewById(R.id.payman);

		View cargoinfo_cargopaytype2 = findViewById(R.id.cargoinfo_cargopaytype2);
		cargoinfo_cargopaytype2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String channelid=app.channelId;
				if (channelid==null) {
					app.getJPushID();
				}
				if (channelid.length()<=0) {
					app.getJPushID();
				}
				showChosepayman();
				UpDataBAIDU_IDtoServer(app.channelId,"null");			
			}
		});
		carryname = (RelativeLayout) findViewById(R.id.addcargo_paytype_layout);

		carryname.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// addcargo_paytype_img
				ImageView imageView = (ImageView) AddCargoOrderActivity.this
						.findViewById(R.id.addcargo_paytype_img);
				TextView textView = (TextView) AddCargoOrderActivity.this
						.findViewById(R.id.carryname);
				// addcargo_paytype_img.setImageResource(R.drawable.ly_pay_img1);
				if (carry_man_need.equals("0")) {
					Log.v("点击了1", "carry_man_need--------->" + carry_man_need);
					imageView.setImageResource(R.drawable.ly_pay_img1);
					carry_man_need = "1";
					textView.setText("是");
					cleanEditViewFocus();

				} else if (carry_man_need.equals("1")) {
					Log.v("点击了1", "carry_man_need------->" + carry_man_need);
					imageView.setImageResource(R.drawable.ly_pay_img);
					carry_man_need = "0";
					textView.setText("否");
					cleanEditViewFocus();

				}

			}
		});

		insure = (TextView) findViewById(R.id.insure);

		callbacklist = (RelativeLayout) findViewById(R.id.addcargo_huidan_layout);
		callbacklist.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (needreceipt.equals("1")) {
					ImageView imageView = (ImageView) findViewById(R.id.addcargo_huidan_img);
					imageView.setBackgroundResource(R.drawable.ly_huidan_img); // R.drawable.ly_pay_img
					TextView driver_call = (TextView) findViewById(R.id.driver_call);
					driver_call.setText("否");
					needreceipt = "2";
				} else {
					ImageView imageView = (ImageView) findViewById(R.id.addcargo_huidan_img);
					imageView.setBackgroundResource(R.drawable.ly_huidan_img1); // ly_huidan_img
					TextView driver_call = (TextView) findViewById(R.id.driver_call);
					driver_call.setText("是");
					needreceipt = "1";
				}
			}
		});

		cargoremark = (TextView) findViewById(R.id.cargoremark);

		photo1 = (ImageView) findViewById(R.id.photo1);
		photo1.setOnClickListener(imageClick);
		photo2 = (ImageView) findViewById(R.id.photo2);
		photo2.setOnClickListener(imageClick);
		photo3 = (ImageView) findViewById(R.id.photo3);
		photo3.setOnClickListener(imageClick);
		systeamprice = (Button) findViewById(R.id.systeamprice);

		upload = (Button) findViewById(R.id.upload);
		upload.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				SaveDataToMap();
			}
		});


		final TextView need_car_time = (TextView) findViewById(R.id.need_car_time);

		need_car_time.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				DatePickerFragment datePickerFragment = new DatePickerFragment(
						AddCargoOrderActivity.this, null, true, "请选择您的预约用车时间",
						"取消用车时间");
				datePickerFragment.setNeedTomorrow(true);
				datePickerFragment.setOnChoseData(new onChoseData() {

					@Override
					public void getChoseData(Boolean isChose, String dataString) {
						// TODO Auto-generated method stub
						// duesenddate
						if (isChose) {
							infoMap.put("duesenddate", dataString);
						} else {
							infoMap.remove("duesenddate");
						}
					}
				});
				datePickerFragment.dateTimePicKDialog(need_car_time);
			}
		});
		show_receive_view_1 = findViewById(R.id.show_receive_view_1);
		show_receive_view_2 = findViewById(R.id.show_receive_view_2);
		receive_view_1 = findViewById(R.id.receive_view_1);
		receive_view_2 = findViewById(R.id.receive_view_2);
		show_receive_view_1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				if ((receive_view_1.getVisibility() == 0)
						&& (receive_view_2.getVisibility() == 8)) {
					receive_view_1.setVisibility(View.GONE);
					show_receive_view_2.setVisibility(View.GONE);
					TextView textView = (TextView) show_receive_view_1
							.findViewById(R.id.show_receive_view_Text_1);
					textView.setText("点击添加收货人(2)");
					receive_2_open = false;
					return;
				}
				if ((receive_view_1.getVisibility() == 8)) {
					receive_view_1.setVisibility(View.VISIBLE);
					show_receive_view_2.setVisibility(View.VISIBLE);
					TextView textView = (TextView) show_receive_view_1
							.findViewById(R.id.show_receive_view_Text_1);
					textView.setText("收货人信息(2)（选填）");
					receive_2_open = true;
					Log.v("点击了show_receive_view_1", "----->" + receive_2_open);
				}
			}
		});

		show_receive_view_2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if ((receive_view_2.getVisibility() == 0)) {
					receive_view_2.setVisibility(View.GONE);
					TextView textView = (TextView) show_receive_view_2
							.findViewById(R.id.show_receive_view_Text_2);
					textView.setText("点击添加收货人(3)");
					receive_3_open = false;
					Log.v("点击了receive_view_2", "----->" + receive_3_open);
					return;
				}
				if ((receive_view_2.getVisibility() == 8)) {
					receive_view_2.setVisibility(View.VISIBLE);
					TextView textView = (TextView) show_receive_view_2
							.findViewById(R.id.show_receive_view_Text_2);
					textView.setText("收货人信息(3)（选填）");
					receive_3_open = true;
					Log.v("点击了receive_view_2", "----->" + receive_3_open);
				}
			}
		});
	}

	private void cleanEditViewFocus() {
		cargoname.clearFocus();
		cargophone.clearFocus();
		origin.clearFocus();
		receivername_1.clearFocus();
		receiverphone_1.clearFocus();
		destination_1.clearFocus();
		receivername_2.clearFocus();
		receiverphone_2.clearFocus();
		receivername_3.clearFocus();
		receiverphone_3.clearFocus();
	}

	private void showChosepayman() {
		// TODO Auto-generated method stub
		InPutDialog inPutDialog = new InPutDialog(this, "请选择付款人", null, null,
				null);
		inPutDialog.setGetChoseTYPE(new getChoseTYPE() {

			@Override
			public void getImageTYPE(int type) {
				// TODO Auto-generated method stub
				if (type == 1) {
					pay_man = "2";
					payman.setText("收货人付款");

				}
				if (type == 2) {
					pay_man = "1";
					payman.setText("发货人付款");
				}
			}
		});
		inPutDialog.getPhotoDialog("收货人付款", "发货人付款");
	}

	private void showChosepayway() {
		// TODO Auto-generated method stub
		InPutDialog inPutDialog = new InPutDialog(this, "请选择付款方式", null, null,
				null);
		inPutDialog.setGetChoseTYPE(new getChoseTYPE() {

			@Override
			public void getImageTYPE(int type) {
				// TODO Auto-generated method stub
				if (type == 1) {
					pay_way = "1";
					payway.setText("线下");
				}
				if (type == 2) {
					pay_way = "2";
					payway.setText("线上");
				}
			}
		});
		inPutDialog.getPhotoDialog("线下支付", "线上支付");
	}


	private void GetAddress(int viewid) {
		flag = "0";
		Intent intent = new Intent(this, AddCargoMapActivity.class);
		startActivityForResult(intent, viewid);

	}

	class ActionClick implements OnClickListener {

		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.destination_1:
				GetAddress(R.id.destination_1);
				break;
			case R.id.destination_2:
				GetAddress(R.id.destination_2);
				break;
			case R.id.destination_3:
				GetAddress(R.id.destination_3);
				break;
			case R.id.origin:

				GetAddress(R.id.origin);
			default:
				break;
			}
		}

	}

	class ImageClick implements OnClickListener {

		@Override
		public void onClick(View imageview) {
			// TODO Auto-generated method stub
			switch (imageview.getId()) {
			case R.id.photo1:
				addImg(R.id.photo1);
				break;
			case R.id.photo2:
				addImg(R.id.photo2);
				break;
			case R.id.photo3:
				addImg(R.id.photo3);
				break;
			default:
				break;
			}
		}

	}

	// /**************百度地图*****************************************
	// @Override
	// public void onGetGeoCodeResult(GeoCodeResult arg0) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
	// // TODO Auto-generated method stub
	//
	// }

	/**
	 * 拍照
	 */
	private void addImg(final int ImageID) {

		new AlertDialog.Builder(AddCargoOrderActivity.this)
				.setTitle("上传图片")
				.setItems(new String[] { "拍照上传", "上传手机中的照片" },
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								Intent intent = null;
								switch (which) {
								case 0:

									FileUtils.createDirFile(IMAGE_PATH);
									intent = new Intent(
											MediaStore.ACTION_IMAGE_CAPTURE);
									String path = IMAGE_PATH
											+ UUID.randomUUID().toString()
											+ ".jpg";
									File file = FileUtils.createNewFile(path);
									if (file != null) {
										intent.putExtra(
												MediaStore.EXTRA_OUTPUT,
												Uri.fromFile(file));
									}
									flag = "1";
									mTakePicturePath = path;
									startActivityForResult(intent, ImageID);

									break;

								case 1:

									Intent intent2 = new Intent(
											Intent.ACTION_PICK, null);
									intent2.setDataAndType(
											MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
											"image/*");
									flag = "2";
									startActivityForResult(intent2, ImageID);
									break;
								}
							}
						})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).create().show();

	}
	private void SetImageToUi(Intent data, int imageId) {
		ImageView imageview;
		Uri uri = data.getData();
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, proj, null, null, null);
		if (cursor != null) {
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			if (cursor.getCount() > 0 && cursor.moveToFirst()) {
				String path = cursor.getString(column_index);

				Log.v("图片路径", path);
				// mTakePicturePath = path;
				// System.out.println("mTakePicturePath"+mTakePicturePath);
				if (path != null) {
					ImageFactory.compressImage(path, 10);
					imageview = (ImageView) findViewById(imageId);
					BitmapUtils utils = new BitmapUtils(this);
					utils.display(imageview, path);

					if (imageId == R.id.photo1) {
						imageMap.put("photos", path);
						// s.add(path);
					}
					if (imageId == R.id.photo2) {
						imageMap.put("photos1", path);
						// s.add(path);
					}
					if (imageId == R.id.photo3) {
						imageMap.put("photos2", path);
						// s.add(path);
					}
					// imageMap1.put("photos", s);
				}
				// upPz(path, bitmap);

			}
		}
		// this.setUserPhoto(bitmap);
	}

	private void SaveDataToMap() {
		if (!TextUtils.isEmpty(cargoname.getText().toString().trim())) {
			infoMap.put("shippername", cargoname.getText().toString().trim());
		} else {
			Toast.makeText(this, "请输入发货人姓名", Toast.LENGTH_LONG).show();
			return;
		}
		if (!TextUtils.isEmpty(cargophone.getText().toString().trim())) {
			if ((cargophone.getText().toString().trim().length() == 11)
					|| (cargophone.getText().toString().trim().length() == 8)) {
				infoMap.put("shipperphone", cargophone.getText().toString()
						.trim());
			} else {
				Toast.makeText(this, "发货人电话不正确", Toast.LENGTH_LONG).show();
				return;
			}
		} else {
			Toast.makeText(this, "请输入发货人电话", Toast.LENGTH_LONG).show();
			return;
		}
		if (!TextUtils.isEmpty(origin.getText().toString().trim())) {
			infoMap.put("origin", origin.getText().toString().trim());
			Gson jGson = new Gson();
			String json = jGson.toJson(originCoordinate);
			infoMap.put("originCoordinate", json);
		} else {
			Toast.makeText(this, "请输入发货地", Toast.LENGTH_LONG).show();
			return;
		}
		List<passlocations> passlocations = new ArrayList<passlocations>();
		passlocations dat_1 = new passlocations();
		passlocations dat_2 = new passlocations();
		passlocations dat_3 = new passlocations();

		String receive_1 = receiverphone_1.getText().toString().trim();
		String recivername_1 = receivername_1.getText().toString().trim();
		String reciverdestin_1 = destination_1.getText().toString().trim();

		if (((receive_1 != null) && (receive_1.length() > 0))
				&& ((receive_1.length() == 11) || (receive_1.length() == 8))) {
			if ((recivername_1 != null) && (recivername_1.length() > 0)) {
				if ((reciverdestin_1 != null) && (reciverdestin_1.length() > 0)) {
					dat_1.setReceiverphone(receive_1);
					dat_1.setReceivername(recivername_1);
					dat_1.setDestination(reciverdestin_1);
					Gson jGson = new Gson();
					String json = jGson.toJson(saveGeoCode[0]);
					dat_1.setCoordinate(json);
					passlocations.add(dat_1);
				} else {
					Toast.makeText(this, "请输入收货人地址", Toast.LENGTH_LONG).show();
					return;
				}
			} else {
				Toast.makeText(this, "请输入收货货人名字", Toast.LENGTH_LONG).show();
				return;
			}
		} else {
			Toast.makeText(this, "请输入正确的收货人电话", Toast.LENGTH_LONG).show();
			return;
		}
		if (receive_2_open) {

			String receiverp_2 = receiverphone_2.getText().toString().trim();
			String receiverna_2 = receivername_2.getText().toString().trim();
			String destinatio_2 = destination_2.getText().toString().trim();
			if ((receiverp_2 != null)
					&& (receiverp_2.length() > 0)
					&& ((receiverp_2.length() == 11) || (receiverp_2.length() == 8))) {
				if ((receiverna_2 != null) && (receiverna_2.length() > 0)) {
					if ((destinatio_2 != null) && (destinatio_2.length() > 0)) {
						dat_2.setReceiverphone(receiverp_2);
						dat_2.setReceivername(receiverna_2);
						dat_2.setDestination(destinatio_2);
						Gson jGson = new Gson();
						String json = jGson.toJson(saveGeoCode[1]);
						dat_2.setCoordinate(json);
						passlocations.add(dat_2);
					} else {
						Toast.makeText(this, "请输入收货人地址", Toast.LENGTH_LONG)
								.show();
						return;
					}
				} else {
					Toast.makeText(this, "请输入收货人名字", Toast.LENGTH_LONG).show();
					return;
				}
			} else {
				Toast.makeText(this, "请输入正确的收货人电话", Toast.LENGTH_LONG).show();
				return;
			}

		}
		if (receive_3_open) {
			String receiverna_3 = receivername_3.getText().toString().trim();
			String destinatio_3 = destination_3.getText().toString().trim();
			String receiverph_3 = receiverphone_3.getText().toString().trim();
			if ((receiverna_3 != null) && (receiverna_3.length() > 0)) {
				if ((destinatio_3 != null) && (destinatio_3.length() > 0)) {
					if ((receiverph_3 != null)
							&& (receiverph_3.length() > 0)
							&& ((receiverph_3.length() == 8) || (receiverph_3
									.length() == 11))) {
						dat_3.setReceivername(receiverna_3);
						dat_3.setDestination(destinatio_3);
						dat_3.setReceiverphone(receiverph_3);
						Gson jGson = new Gson();
						String json = jGson.toJson(saveGeoCode[2]);
						dat_3.setCoordinate(json);
						passlocations.add(dat_3);
					} else {
						Toast.makeText(this, "请输入正确的收人电话", Toast.LENGTH_LONG)
								.show();
						return;
					}
				} else {
					Toast.makeText(this, "请输入收货人地址", Toast.LENGTH_LONG).show();
					return;
				}
			} else {
				Toast.makeText(this, "请输入收货人名字", Toast.LENGTH_LONG).show();
				return;
			}
		}
		if (expectprice.getText().toString().length() <= 0) {
			Toast.makeText(this, "请输入期望价格", Toast.LENGTH_LONG).show();
			return;
		}

		// passlocations.add(arg0);
		infoMap.put("destinations", passlocations);

		if (!TextUtils.isEmpty(expectprice.getText().toString().trim())) {
			infoMap.put("expectprice", expectprice.getText().toString().trim());
		} else {
			Toast.makeText(this, "请输入期望价格", Toast.LENGTH_LONG).show();
			return;
		}

		if (pay_man != null) {
			if (pay_man.equals("1")) {
				Log.e("预付", "预付");
				infoMap.put("payment", 0);
			} else {
				Log.e("到付", "到付");
				infoMap.put("payment", 1);
			}

		} else {
			Toast.makeText(AddCargoOrderActivity.this, "请选择付款人",
					Toast.LENGTH_LONG).show();
			return;
		}

		infoMap.put("insure", insure.getText().toString().trim());
		infoMap.put("needreceipt", needreceipt);
		if ((carry_man_need.equals("1"))) {
			infoMap.put("needtransport", 1);
		}
		if (carry_man_need.equals("0")) {
			infoMap.put("needtransport", 0);
		}
		infoMap.put("cargoremark", cargoremark.getText().toString().trim());
		infoMap.put("cargoownerid", app.userId);
		HttpJsonTool httpJsonTool = new HttpJsonTool(this);
		showLoadingDialog("下单中，请稍后");
		httpJsonTool.SetOnLister(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				dismissLoadingDialog();
				super.handleMessage(msg);
				if (msg.what == 1) {
					Toast.makeText(AddCargoOrderActivity.this, "恭喜您下单成功！！",
							Toast.LENGTH_LONG).show();
					AddCargoOrderActivity.this.finish();
				} else {
					Toast.makeText(AddCargoOrderActivity.this,
							(String) msg.obj, Toast.LENGTH_LONG).show();
				}

				// File a=new File(null);
			}
		});
		if (imageMap.size() > 0) {
			httpJsonTool.StartWork(infoMap,
			// "http://192.168.1.122:8080/cqtczh/shippers/placeOrderApp",
					GagApi.OnlineOrder, null, imageMap);
		} else {
			httpJsonTool.StartWork(infoMap,
			// "http://192.168.1.122:8080/cqtczh/shippers/placeOrderApp",
					GagApi.ONLINE_ORDER_WITH_OUT_FILE, null, null);
		}
	}

	private void getGeoCodeResult(String data, final int type) {
		mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

			@Override
			public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onGetGeoCodeResult(GeoCodeResult result) {
				// TODO Auto-generated method stub
				if (result == null
						|| result.error != SearchResult.ERRORNO.NO_ERROR) {

				} else {
					Log.v("获得的地址是---》" + result.getAddress(), result
							.getLocation().toString());
					// LatLng baidu_data=result.getLocation();
					if (type == 1) {
						originCoordinate.put("lat",
								result.getLocation().latitude + "");
						originCoordinate.put("lng",
								result.getLocation().longitude + "");
						address_dataMap.put("originCoordinate",
								originCoordinate);
						upLoadGeoCodeResult();
					}
					if (type == 2) {
						HashMap<String, Object> datamHashMap = new HashMap<String, Object>();
						// saveGeoCode.add(arg0);\
						datamHashMap.put("lat", result.getLocation().latitude
								+ "");
						datamHashMap.put("lng", result.getLocation().longitude
								+ "");
						receiveAddress_2 = true;
//						saveGeoCode.r
						saveGeoCode[0]= datamHashMap;
//						address_dataMap.put("coordinates", saveGeoCode);
						upLoadGeoCodeResult();
					}
					if (type == 3) {
						HashMap<String, Object> datamHashMap = new HashMap<String, Object>();
						// saveGeoCode.add(arg0);\
						datamHashMap.put("lat", result.getLocation().latitude
								+ "");
						datamHashMap.put("lng", result.getLocation().longitude
								+ "");
						receiveAddress_3 = true;
						saveGeoCode[1]= datamHashMap;
						
						upLoadGeoCodeResult();
					}
					if (type == 4) {
						HashMap<String, Object> datamHashMap = new HashMap<String, Object>();
						// saveGeoCode.add(arg0);\
						datamHashMap.put("lat", result.getLocation().latitude
								+ "");
						datamHashMap.put("lng", result.getLocation().longitude
								+ "");
						// if (leng == 3) {
						// receiveAddress_4=true;
						// saveGeoCode.add(datamHashMap);
						// address_dataMap.put("coordinates", saveGeoCode);
						// } else {
						receiveAddress_4 = true;
						saveGeoCode[2]=datamHashMap;
//						address_dataMap.put("coordinates", saveGeoCode);
						// }
						upLoadGeoCodeResult();
					}
				}
			}
		});
		mSearch.geocode(new GeoCodeOption().city("重庆市").address(data));
	}

	private void countRoutPrice() {
		address_dataMap.put("carTypeId", cartype);
		if (origin.getText().toString().length() > 0) {
			address_dataMap.put("origin", origin.getText().toString());
			receiveAddress_1 = true;
			// getGeoCodeResult(origin.getText().toString(),1);
		} else {
			return;
		}
		List<String> destinations = new ArrayList<String>();
		String d_a = destination_1.getText().toString();
		String d_b = destination_2.getText().toString();
		String d_c = destination_3.getText().toString();
		if (d_a.length() > 0) {
			destinations.add(d_a);
			address_tyep = 2;
		} else {
		}
		if (d_b.length() > 0) {
			destinations.add(d_b);
			address_tyep = 3;
		}
		if (d_c.length() > 0) {
			destinations.add(d_c);
			address_tyep = 4;
		}
		if (destinations.size() > 0) {
			address_dataMap.put("destinations", destinations);
		} else {
			return;
		}
	}

	private void upLoadGeoCodeResult() {
		Log.v("upLoadGeoCodeResult", "type是---》" + address_tyep);
		boolean flag = false;
		if (originCoordinate.size() <= 0) {
			return;
		}

		for (int i = 0; i < 3; i++) {
			if (!(saveGeoCode[i].isEmpty())) {
				flag = true;
			}
		}
		address_dataMap.remove("coordinates");
		address_dataMap.put("coordinates", saveGeoCode);
		if (!flag) {
			return;
		}

		HttpJsonTool httpJsonTool = new HttpJsonTool(this);
		httpJsonTool.SetOnLister(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if (msg.what == 1) {
					Toast.makeText(AddCargoOrderActivity.this,
							"Q货的 提供给您的价格范围是" + msg.obj.toString(),
							Toast.LENGTH_LONG).show();
					setRoutPriceToUi(msg.obj.toString());
					infoMap.put("suggestprice", msg.obj.toString());
				}
			}
		});
		httpJsonTool.StartWork(address_dataMap, GagApi.HOST
				+ "shippers/calcPriceApp", null, null);
	}

	private void setRoutPriceToUi(String price) {
		if (price == null || price.length() <= 0) {
			return;
		}
		TextView suggestprice = (TextView) findViewById(R.id.suggestprice);
		suggestprice.setText("￥ " + price + "元");
		Button systeamprice = (Button) findViewById(R.id.systeamprice);
		systeamprice.setText("￥ " + price + "元");
	}

	private void SetImageToUi(int imageId) {
		// Log.v("SetImageToUi", "图片路径" + mTakePicturePath);
		if (mTakePicturePath.length() <= 0) {
			Toast.makeText(this, "SetImageToUi-》》路径不见了", Toast.LENGTH_LONG)
					.show();
			return;
		}
		ImageFactory.compressImage(mTakePicturePath, 10);
		ImageView imageView = (ImageView) findViewById(imageId);
		BitmapUtils bitmapUtils = new BitmapUtils(this);
		bitmapUtils.display(imageView, mTakePicturePath);
		if (imageId == R.id.photo1) {
			imageMap.put("photos", mTakePicturePath);
		}
		if (imageId == R.id.photo2) {
			imageMap.put("photos1", mTakePicturePath);
		}
		if (imageId == R.id.photo3) {
			imageMap.put("photos2", mTakePicturePath);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		String aString;
		Log.v("获得的Flag是", "" + flag + "\\" + resultCode);

		if (requestCode == 0) {
			return;
		}
		if (resultCode == 0) {

			return;
		}

		if (resultCode == 5201) {

			LinkManBeen linkManBeen = (LinkManBeen) data
					.getSerializableExtra("linkman");

			infoMap.put("appointid", linkManBeen.getCarownerid());
			TextView textView = (TextView) findViewById(R.id.linkman_info);
			textView.setText(linkManBeen.getCarownername());

		}

		if (flag.equals("0")) {
			if (!StringUtils.isEmpty(data.getStringExtra("address"))) {
				aString = data.getStringExtra("address");
				TextView view = (TextView) findViewById(requestCode);
				view.setTextColor(Color.BLACK);
				view.setText(aString);
				countRoutPrice();
				if (requestCode == R.id.origin) {
					getGeoCodeResult(aString, 1);
				}
				if (requestCode == R.id.destination_1) {
					getGeoCodeResult(aString, 2);
				}
				if (requestCode == R.id.destination_2) {
					getGeoCodeResult(aString, 3);
				}
				if (requestCode == R.id.destination_3) {
					getGeoCodeResult(aString, 4);
				}

			}
		}
		if (flag.equals("1")) {

			if (mTakePicturePath == null) {
				// Toast.makeText(this, "onActivityResult-》》路径不见了",
				// Toast.LENGTH_LONG).show();
				return;
			}
			if (mTakePicturePath.length() <= 0) {
				// Toast.makeText(this, "onActivityResult-》》路径不见了",
				// Toast.LENGTH_LONG).show();
				return;
			}
			SetImageToUi(requestCode);
		}

		if (flag.equals("2")) {
			if (data == null) {
				return;
			}
			SetImageToUi(data, requestCode);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private Bundle activityDestorySaveData() {
		Bundle bundle = new Bundle();
		List<Object> passlocations = new ArrayList<Object>();
		passlocations dat_1 = new passlocations();
		passlocations dat_2 = new passlocations();
		passlocations dat_3 = new passlocations();

		String receive_1 = receiverphone_1.getText().toString().trim();
		String recivername_1 = receivername_1.getText().toString().trim();
		String reciverdestin_1 = destination_1.getText().toString().trim();
		if ((receive_1 != null) && (receive_1.length() > 0)) {
			if ((recivername_1 != null) && (recivername_1.length() > 0)) {
				if ((reciverdestin_1 != null) && (reciverdestin_1.length() > 0)) {
					dat_1.setReceiverphone(receive_1);
					dat_1.setReceivername(recivername_1);
					dat_1.setDestination(reciverdestin_1);
					passlocations.add(dat_1);
				}
			}
		}

		String receiverp_2 = receiverphone_2.getText().toString().trim();
		String receiverna_2 = receivername_2.getText().toString().trim();
		String destinatio_2 = destination_2.getText().toString().trim();
		if ((receiverp_2 != null) && (receiverp_2.length() > 0)) {
			if ((receiverna_2 != null) && (receiverna_2.length() > 0)) {
				if ((destinatio_2 != null) && (destinatio_2.length() > 0)) {
					dat_2.setReceiverphone(receiverp_2);
					dat_2.setReceivername(receiverna_2);
					dat_2.setDestination(destinatio_2);
					passlocations.add(dat_2);
				}
			}
		}

		String receiverna_3 = receivername_3.getText().toString().trim();
		String destinatio_3 = destination_3.getText().toString().trim();
		String receiverph_3 = receiverphone_3.getText().toString().trim();
		if ((receiverna_3 != null) && (receiverna_3.length() > 0)) {
			if ((destinatio_3 != null) && (destinatio_3.length() > 0)) {
				if ((receiverph_3 != null) && (receiverph_3.length() > 0)) {
					dat_3.setReceivername(receiverna_3);
					dat_3.setDestination(destinatio_3);
					dat_3.setReceiverphone(receiverph_3);
					passlocations.add(dat_3);
				}
			}
		}
		// passlocations.add(arg0);
		// List<Object>
		ArrayList list = new ArrayList();
		list.add(passlocations);
		bundle.putParcelableArrayList("destinations", list);
		bundle.putString("shippername", cargoname.getText().toString().trim());
		bundle.putString("shipperphone", cargophone.getText().toString().trim());
		bundle.putString("origin", origin.getText().toString().trim());
		bundle.putString("expectprice", expectprice.getText().toString().trim());
		bundle.putString("payway", payway.getText().toString().trim());
		bundle.putString("payman", payman.getText().toString().trim());
		bundle.putString("insure", insure.getText().toString().trim());
		bundle.putString("payman", payman.getText().toString().trim());
		bundle.putString("needreceipt", needreceipt);
		bundle.putString("carryman", carry_man_need);
		bundle.putString("cargoremark", cargoremark.getText().toString().trim());
		bundle.putString("cargoownerid", app.userId);
		return bundle;
	}

	private void getSaveData(Bundle bundle) {

		ArrayList listdata = new ArrayList();
		listdata = bundle.getParcelableArrayList("destinations");
		List<passlocations> passlocations = (List<javabeen.passlocations>) listdata
				.get(0);

		int i = passlocations.size();
		if (i == 1) {
			receivername_1.setText(passlocations.get(0).getReceivername());
			receiverphone_1.setText(passlocations.get(0).getReceiverphone());
		}
		if (i == 2) {
			receivername_1.setText(passlocations.get(0).getReceivername());
			receiverphone_1.setText(passlocations.get(0).getReceiverphone());
			receivername_2.setText(passlocations.get(1).getReceivername());
			receiverphone_2.setText(passlocations.get(1).getReceiverphone());
		}
		if (i == 3) {
			receivername_1.setText(passlocations.get(1).getReceivername());
			receiverphone_1.setText(passlocations.get(1).getReceiverphone());
			receivername_2.setText(passlocations.get(1).getReceivername());
			receiverphone_2.setText(passlocations.get(1).getReceiverphone());
			receivername_3.setText(passlocations.get(2).getReceivername());
			receiverphone_3.setText(passlocations.get(2).getReceiverphone());
		}

		cargoname.setText(bundle.getString("shippername"));
		cargophone.setText(bundle.getString("shipperphone"));
		origin.setText(bundle.getString("origin"));
		expectprice.setText(bundle.getString("expectprice"));
		payway.setText(bundle.getString("payway"));
		payman.setText(bundle.getString("payman"));
		insure.setText(bundle.getString("insure"));
		needreceipt = bundle.getString("needreceipt");
		if (needreceipt.equals("1")) {

			ImageView imageView = (ImageView) findViewById(R.id.addcargo_huidan_img);
			imageView.setBackgroundResource(R.drawable.ly_huidan_img); // R.drawable.ly_pay_img
			needreceipt = "2";
		} else {

			ImageView imageView = (ImageView) findViewById(R.id.addcargo_huidan_img);
			imageView.setBackgroundResource(R.drawable.ly_huidan_img1); // ly_huidan_img
			needreceipt = "1";
		}
		carry_man_need = bundle.getString("carryman");
		cargoremark.setText(bundle.getString("cargoremark"));
		app.userId = bundle.getString("cargoownerid");
	}

	
	
	private void UpDataBAIDU_IDtoServer(String channelId_app, String userId_app) {
		HashMap<String, String> dataMap = new HashMap<String, String>();
		dataMap.put("channelid", channelId_app);
		dataMap.put("userid", "null");
		dataMap.put("cargoownerid", app.userId);
		HttpJsonTool httpJsonTool = new HttpJsonTool(this);

		httpJsonTool.SetOnLister(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
			}
		});
		httpJsonTool.StartWork(dataMap, GagApi.PUSH_UP_DATA_URL, null, null);
		if (app.userinfobeen != null) {

		} else {
			Intent intent = new Intent(this, UserLoginActivity.class);
			startActivity(intent);
		}
	}
	
	
	
	
	// onSaveInstanceState
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putAll(activityDestorySaveData());
	}
}
